import {
  reqOrderAddress,
  reqOrderDetail,
  reqBuyGoods,
  reqSubmitOrder,
  reqPrePayinfo,
  reqPayStatus
} from '../../../api/oderPay'
import Schema from 'async-validator'

import { formatTime } from '../../../utils/formatTime'

//导入防抖函数
import { debounce } from 'miniprogram-licia'
const app = getApp()
Page({
  data: {
    buyName: '', // 订购人姓名
    buyPhone: '', // 订购人手机号
    deliveryDate: '', // 期望送达日期
    blessing: '', // 祝福语
    show: false, // 期望送达日期弹框
    orderAddress: {}, //收货地址
    orderInfo: {}, //订单商品详情
    minDate: new Date().getTime(),
    currentDate: new Date().getTime()
  },

  //处理提交订单
  submitOrder: debounce(async function () {
    //需要从data获取数据 再把数据组织
    const {
      buyName,
      buyPhone,
      deliveryDate,
      blessing,
      orderAddress,
      orderInfo
    } = this.data
    //需要根据接口组织参数
    const params = {
      buyName,
      buyPhone,
      cartList: orderInfo.cartVoList,
      deliveryDate,
      remarks: blessing,
      userAddressId: orderAddress.id
    }
    const res = await this.vaildatorPerson(params)
    //请求失败
    if (!res) return

    //创建平台订单调用接口
    const OrderRes = await reqSubmitOrder(params)
    if (OrderRes.code === 200) {
      this.OrderNo = OrderRes.data
      //获取预付单信息
      this.advancePay()
    }
  }, 500),
  //预付单
  async advancePay() {
    try {
      const Payams = await reqPrePayinfo(this.OrderNo)
      if (Payams.code == 200) {
        //Payams.data获取支付参数
        // console.log()

        const Payinfo = await wx.requestPayment(Payams.data)
        if (Payinfo.errMsg === 'requestPayment:ok') {
          //校验订单
          const payStatus = await reqPayStatus(this.OrderNo)
          if (payStatus.code === 200) {
            wx.redirectTo({
              url: '/modules/orderPayModules/pages/order/list/list',
              success: () => {
                wx.toast({
                  title: '政府成功',
                  icon: 'success'
                })
              }
            })
          }
        }
      }
    } catch (error) {
      console.log(error)
      wx.toast({
        title: '支付失败请联系客服',
        icon: 'error'
      })
    }
  },
  //校验收货人订购人参数进行验证
  vaildatorPerson(params) {
    // 验证订购人收货人，是否只包含大小写字母、数字和中文字符
    const nameRegExp = '^[a-zA-Z\\d\\u4e00-\\u9fa5]+$'

    // 验证订购人手机号，是否符合中国大陆手机号码的格式
    const phoneReg = '^1(?:3\\d|4[4-9]|5[0-35-9]|6[67]|7[0-8]|8\\d|9\\d)\\d{8}$'

    //创建验证规则
    const rules = {
      userAddressId: [
        {
          required: true,
          message: '请选择收货地址'
        }
      ],
      buyName: [
        {
          required: true,
          message: '请输入订购人姓名'
        },
        {
          pattern: nameRegExp,
          message: '订购人姓名不合法'
        }
      ],
      buyPhone: [
        {
          required: true,
          message: '请输入订购人手机号'
        },
        {
          pattern: phoneReg,
          message: '订购人手机号不合法'
        }
      ],
      deliveryDate: { required: true, message: '请选择送达日期' }
    }

    //验证规则
    const vaildator = new Schema(rules)

    //调用实例方法对请求参数进行验证
    return new Promise((reslove) => {
      vaildator.validate(params, (errors) => {
        if (errors) {
          //如果验证失败 进行提示
          wx.toast({
            title: errors[0].message
          })
          reslove({ valid: false })
        } else {
          //验证成功
          reslove({ valid: true })
        }
      })
    })
  },

  // 选择期望送达日期
  onShowDateTimerPopUp() {
    this.setData({
      show: true
    })
  },

  // 期望送达日期确定按钮
  onConfirmTimerPicker(event) {
    const wantTime = formatTime(new Date(event.detail))
    // console.log(wantTime)
    this.setData({
      show: false,
      //时间
      deliveryDate: wantTime
    })
  },

  // 期望送达日期取消按钮 以及 关闭弹框时触发
  onCancelTimePicker() {
    this.setData({
      show: false,
      minDate: new Date().getTime(),
      currentDate: new Date().getTime()
    })
  },

  // 跳转到收货地址
  toAddress() {
    wx.navigateTo({
      url: '/modules/settingModules/pages/address/add/index'
    })
  },

  //获取订单页面收货地址
  getOrderAddress() {
    //是否存在共享数据 address是否存在数据
    //如果存在数据 就需要从全局共享的address 获取数据进行赋值
    const addressId = app.globalData.address.id
    if (addressId) {
      this.setData({
        orderAddress: app.globalData.address
      })
      return
    }

    reqOrderAddress().then((res) => {
      const { data: orderAddress } = res
      this.setData({
        orderAddress: orderAddress
      })
    })
  },

  //获取订单详情
  async getOrderInfo() {
    const { goodsId, blessing } = this.data
    // console.log(this.data.blessing)
    const { data: orderInfo } = goodsId
      ? await reqBuyGoods({ goodsId, blessing })
      : await reqOrderDetail()

    //判断是否存在祝福,如果是多个商品,则筛选第一个存在祝福语进行赋值
    const orderGoods = orderInfo.cartVoList.find((item) => item.blessing !== '')

    this.setData({
      orderInfo: orderInfo,
      blessing: !orderGoods ? '' : orderGoods.blessing
    })
  },
  onShow() {
    //获取收货地址
    this.getOrderAddress()

    //获取订单详情
    this.getOrderInfo()
  },
  onLoad(options) {
    //获取立即购买传递参数
    //然后把参数赋值给data中的参数
    this.setData({
      ...options
    })
  },

  onUnload() {
    app.globalData.address = {}
  }
})
